# This script will read in a multiple insolation files
# And convert them to 250 m res WTplusBuffer size

# Load library

library('SDMTools')
	
# Define out directory

base.dir = '/home1/99/jc152199/GRASS/ASCIIoutput/'
out.dir = '/home1/99/jc152199/MicroclimateStatisticalDownscale/250mASCII/BC6/'

# Read in base.asc

base.asc = read.asc('/home1/99/jc152199/MicroclimateStatisticalDownscale/250mASCII/STATIC/dem_WTplusbuffer_LatLong_WGS1984_250mres.asc')

# Create positions from base.asc

base.pos = as.data.frame(which(is.na(base.asc)==F, arr.ind = T)) 
base.pos$lat = getXYcoords(base.asc)$x[base.pos$row]
base.pos$long = getXYcoords(base.asc)$y[base.pos$col]

# Get locations of files to convert

insol.originals = list.files(paste(base.dir,sep=''),full.names=T, pattern='insol')
insol.names = gsub('.asc','',list.files(paste(base.dir,sep=''), pattern='insol'))

j=1

for (i in insol.originals)

	{
	
	# Read in BC ASCII
	
	t.asc = read.asc(paste(i,sep=''))

	# Create 250 m res BC ASCII size of WTplusbuffer

	base.asc[cbind(base.pos$row,base.pos$col)] = extract.data(cbind(base.pos$lat,base.pos$long),t.asc)

	# Write out ASCII to appropriate directory

	write.asc.gz(base.asc,paste(out.dir,insol.names[j],sep=''))
	
	cat(j/length(insol.originals),'% Complete\n',sep='')
	
	j=j+1
	
	}

# Done

	
